package com.ahao.service;

import com.ahao.dao.GradeDao;
import com.ahao.model.Grade;
import com.ahao.model.GradeDTO;
import com.ahao.utils.CommonsUtils;
import com.ahao.utils.DBUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class GradeService {
    GradeDao gradeDao = new GradeDao();

    /**
     * 所有年级
     * @return
     */
    public List<GradeDTO> getAllGrades() {
        try {
            return gradeDao.getAllGrades();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加年级
     * @param gradeName
     * @param cids
     * @return
     */
    public Integer addGrade(String gradeName, List<Integer> cids) {
        Connection con = DBUtils.getConnection();
        try {
            //判断是否已经存在该年级
            Grade grade = gradeDao.getGradeByName(gradeName);
            if (grade != null) {
                return CommonsUtils.TABLE_DATA_REPEAT;
            }
            //开启事务
            con.setAutoCommit(false);
            Grade grade1 = new Grade();
            grade1.setGradeName(gradeName);
            Integer integer = gradeDao.addGrade(grade1);
            Integer integer1 = gradeDao.addGardeCourses(grade1.getGid(), cids);
            //提交事务
            con.commit();
            return integer==1&&integer1==cids.size()?CommonsUtils.UPDATE_SUCCESS:CommonsUtils.OTHER_EXCEPTION;
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                //发生异常，回滚事务
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            //关闭连接
            DBUtils.close(con);
        }
        return CommonsUtils.OTHER_EXCEPTION;
    }


    public Integer deleteGradeByGid(Integer gid) {
        Connection con = DBUtils.getConnection();

        try {
            con.setAutoCommit(false);
            Integer i = gradeDao.deleteGradeByGid(gid);
            Integer i2 = gradeDao.deleteGradeCoursesByGid(gid);
            con.commit();
            return i==1?CommonsUtils.UPDATE_SUCCESS:CommonsUtils.OTHER_EXCEPTION;
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally {
            DBUtils.close(con);
        }
        return CommonsUtils.OTHER_EXCEPTION;
    }
}
